<?php
//Yii::import('application.vendors.*');
require_once('diggin-data/dd-functions.php');
class MyController extends Controller
{
    // {{{ *** Members
    /**
     * The default layout for the controller view. Defaults to '//layouts/column1',
     * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
     * @var string 
     */
    public $layout='//layouts/column2sbleft';
    /**
     * context menu items. This property will be assigned to {@link CMenu::items}.
     * @var array 
     */
    public $menu=array();
    /**
     * the breadcrumbs of the current page. The value of this property will
     * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
     * for more details on how to specify this property.
     * @var array
     */
    public $breadcrumbs=array();
    public $title;
    // }}} End Members
    // {{{ init
    /**
     * Initializes the controller
     *
     * Inits the i18n system with php-gettext
     */
    function init()
    {
        if($this->title==null)
            $this->title = $this->name;
        parent::init();
        $app = Yii::app();
        $this->_initIcons();
        // {{{ Set GUI language
        /*
        if (isset($_REQUEST['_lang']))
        {
            Yii::log("[MyController/init] Language change via _GET: ".$_REQUEST['_lang']);
            $app->language = $_REQUEST['_lang'];
            $app->session['_lang'] = $app->language;
            $supportedLocales = $this->getSupportedLocales();
            Yii::app()->user->setFlash('success', '<h4>'.Yii::t('site',"User Interface Language").'</h4>'.Yii::t('site',"The language changed to {lang}",array('{lang}'=>$supportedLocales[$_REQUEST['_lang']])));
        }
        else if (isset($app->session['_lang']) and $app->session['_lang'] !== '')
        {
            Yii::log("[MyController/init] Language found in session: ".$app->session['_lang']);
            $app->language = $app->session['_lang'];
        }
        else if( $app->session['_lang'] == '' )
        {
            Yii::log("[MyController/init] Language not found in session, setting to default: ".Yii::app()->params['default_locale']);
            $app->language = Yii::app()->params['default_locale'];
            $app->session['_lang'] = $app->language;
        }
        else 
        {
            Yii::log("[MyController/init] Set Language to default: ".Yii::app()->params['default_locale']);
            $app->language = Yii::app()->params['default_locale'];
            $app->session['_lang'] = $app->language;
        }
        */
        // }}} 
        // {{{ Init gettext
        /*
        $supported_locales = $app->params['supported_locales'];
        $encoding = 'UTF-8';
        if (strtoupper(substr(php_uname('s'), 0, 3)) === 'WIN') { 
            if(!putenv("LANGUAGE=".$app->language)) dbg("Cant't set LANG"); 
            // windows workaround for LC_MESSAGES 
            if (!defined('LC_MESSAGES')) {
                //dbg("Defining LC_MESSAGES" );
                //define('LC_MESSAGES', 6);
            }
        }
        // Set the text domain as 'messages'
        $domain = 'messages';
        define('LOCALE_DIR', str_replace("\\", "/", Yii::app()->basePath).'/messages/');
        dbg('LOCALE_DIR: '.LOCALE_DIR);
        dbg("Setting locale: ".setlocale(LC_ALL, $app->language));
	//setlocale(LC_ALL, $app->language);
	// path to the .MO file that we should monitor
	$filename = LOCALE_DIR."{$app->language}/LC_MESSAGES/{$domain}.mo";
	$mtime = filemtime($filename); // check its modification time
	// our new unique .MO file
	$filename_new =  LOCALE_DIR."{$app->language}/LC_MESSAGES/{$domain}_{$mtime}.mo"; 
	if (!file_exists($filename_new)) {  // check if we have created it before
	    // if not, create it now, by copying the original
	    copy($filename,$filename_new);
	}
	// compute the new domain name
	$domain_new = "{$domain}_{$mtime}";
	
	dbg("bindtextdomain: ".bindtextdomain($domain_new, LOCALE_DIR));
	bind_textdomain_codeset($domain_new,$encoding);
        textdomain($domain_new);
         */
        // }}} 
        define('DEC_PT',    Yii::t('site','DecimalPoint'));
        define('TH_SEP',    Yii::t('site','ThousandsSeparator'));
        // Strings
        $strings = array(
            'Guest' => Yii::t('site','Guest'),
            'Contact Webmaster' => Yii::t('site','Contact Webmaster'),
            'Imprint' =>Yii::t('site','Imprint'), 
            'Toggle Sidebar' => Yii::t('site','Toggle Sidebar'),
        );
    } // }}} 
    // {{{ setFlash
    /**
     * Adds a flash message for created, updated or deleted model
     *
     * @param   string  $action Either create, update or delete
     * @param   mixed   &$model  reference to model
     */
    public function setFlash( $action, &$model, $type='success' )
    {
        switch( $action)
        {
            case 'create':
                $title  = Yii::t('site','Creating Item');
                $msg    = Yii::t('site',"The item <em>{item}</em> has been created.",array('{item}'=>$model->getRecordName()));
                break;
            case 'update':
                $title  = Yii::t('site','Updating Item');
                $msg    = Yii::t('site',"The item <em>{item}</em> has been updated.",array('{item}'=>$model->getRecordName()));
                break;
            case 'delete':
                $title  = Yii::t('site','Deleting Item');
                $msg    = Yii::t('site',"The item <em>{item}</em> has been deleted.",array('{item}'=>$model->getRecordName()));
                break;
            default:
                if( is_array($action) and count($action)==2 ) {
                    $title = $action[0];
                    $msg = $action[1];
                } else {
                    $title=Yii::t('site','Message');
                    $msg = $action;
                }
                break;
        }
        Yii::app()->user->setFlash(
            $type,
            sprintf(
                "<strong>%s</strong><br/><br/>%s",
                $title,$msg
            )
        );
    } // }}}
    // {{{ setSiteFlash
    public function setSiteFlash($type,$message)
    {
        $_SESSION['flash'][$type][] = $message;
    } // }}} 
    // {{{ accessRules
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to access 'index' and 'view' actions.
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated users to access all actions
                'users'=>array('@'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    } // }}} 
    // {{{ checkAccess
    /**
     * Checks if current user has access for auth item
     *
     * @param   string  $itemName   Auth item name
     */
    public function checkAccess( $itemName )
    {
        if(!Yii::app()->user->checkAccess($itemName) or Yii::app()->user->isGuest) {
            // {{{ Store last query args
            $url = parse_url($_SERVER['HTTP_REFERER']);
            // get an array of 'key=value' strings
            $argsStrings = explode('&',$url['query']);
            // Just one arguemnt?
            if(count($argsStrings)==0)
                $argsStrings = array($url['query']);
            $args = array();
            // Split up key, value
            foreach($argsStrings as $argString) {
                if(preg_match("/(.*)=(.*)/",$argString,$matches)) {
                    $args[$matches[1]] = $matches[2];
                } else {
                    $args[$argString] = '';
                }
            }
            // Do we have the last request(r arg)?
            if(isset($args['r'])) {
                $redirect = array($args['r']);
                unset($args['r']);
                // Add all other query args
                foreach($args as $key=>$value)
                    $redirect[$key] = $value;
            } else {
                // No args were given, redirect to site root
                $redirect = array('/');
            }
            // }}} 
            // DEBUG echo par($redirect);
            $this->setFlash(
                array(
                    Yii::t('site','Special Privileges required!'),
                    Yii::t('site',"Sorry, you don't have enough privileges to perform this task.")
                ),
                $dummy=array(),
                'error'
            );
            $this->redirect($redirect);
        }
    } // }}} 
    // {{{ prepareDateFields
    /**
     * Prepares date attributes according to the UI locale
     *
     * @param   mixed   &$model Model instance
     */
    public function prepareDateFields( &$model )
    {
        $schema = $model->getTableSchema();
        $dateFormatter = Yii::app()->dateFormatter;
        foreach( $schema->columns as $column ) {
            // DEBUG echo "<li>$columnName: ".$model->$columnName . ": " . $column->dbType;
            if( $column->dbType=='date' ) {
		$columnName =  $column->name;
                // DEBUG echo "<li>$columnName: ".$model->$columnName;
                if( $model->$columnName=='0000-00-00' ) {
		    $model->$columnName = '';
		} elseif(trim($model->$columnName)=='') {
		    $model->$columnName='';
                } else {
                    //$dateFormat = CLocale::getInstance(Yii::app()->language)->getDateFormat('medium');
                    //if(CDateTimeParser::parse($model->$columnName, $dateFormat)!==false) {
    		        list($year,$month,$day) = explode( '-', $model->$columnName );
                        // DEBUG echo "<li>year: $year, month: $month, day: $day";
                        $model->$columnName = $dateFormatter->formatDateTime( 
                            mktime(0,0,0,$month,$day,$year),'medium',null
                        );
                        // DEBUG echo "<li>New Value: ".$model->$columnName;
                    // }
                }
            }
        }
    } // }}} 
    // {{{ prepareNumericFields
    /**
     * Prepares float/decimal fields according to the UI locale
     *
     * @param   mixed   &$model Model instance
     */
    public function prepareNumericFields( &$model )
    {
        $schema = $model->getTableSchema();
        foreach( $schema->columns as $column ) {
            // DEBUG echo "<li>{$column->name}: {$column->dbType}";
            if( preg_match("/decimal|float/", $column->dbType ) ) {
                $columnName =  $column->name;
                $model->$columnName = str_replace('.', ',', $model->$columnName);
            }
        }
    } // }}}
    // {{{ prepareBoolFields
    /**
     * Prepares tinyint fields as textual checkboxes
     *
     * @param   mixed   &$model Model instance
     */
    public function prepareBoolFields( &$model )
    {
        $schema = $model->getTableSchema();
        foreach( $schema->columns as $column ) {
            if( preg_match("/tinyint\(1\)|bool/", $column->dbType ) ) {
                $columnName     = $column->name;
                $model->$columnName = $model->$columnName==1 ? ICON_CHECK_1 : ICON_CHECK_0;
            }
        }
    } // }}}
    // {{{ _initIcons
    /**
     * Initializes the icons constants
     */
    private function _initIcons()
    {
        $basePath = Yii::app()->baseUrl.'/images/icons';
        $tag = "<img src=\"{$basePath}/%s\" border=\"0\" align=\"middle\" /> ";
        // New
        define('ICON_NEW', sprintf( $tag, 'new.png'));
        // Copy
        define('ICON_COPY', sprintf( $tag, 'copy.png'));
        // Save
        define('ICON_SAVE', sprintf( $tag, 'save.png'));
        // View
        define('ICON_VIEW', sprintf( $tag, 'b_view.png'));
        // Edit
        define('ICON_EDIT', sprintf( $tag, 'edit.gif'));
        // Delete
        define('ICON_DELETE', sprintf( $tag, 'delete.png' /* trash.png' */ ));
        // Undo
        define('ICON_UNDO', sprintf( $tag, 'redo.png'));
        // Check 0
        define('ICON_CHECK_0', sprintf( $tag, 'check_0.png'));
        // Check 1
	define('ICON_CHECK_1', sprintf( $tag, 'check_1.png'));
        // Calendar
	define('ICON_CALENDAR', sprintf( $tag, 'calendar.png'));
        // Print
	define('ICON_PRINT', sprintf( $tag, 'print.png'));

    } // }}} 
    // {{{ getPagerSettings
    public function getPagerSettings($pages)
    {
        $defaults = array(
            'header'            => henc(sprintf(ngettext('%d Item.','%d Items',$pages->itemCount),$pages->itemCount)).'&nbsp;&nbsp;&nbsp;',
            'firstPageLabel'    => Yii::t('site','First'),
            'prevPageLabel'     => '< '.Yii::t('site','Previous'),
            'nextPageLabel'     => Yii::t('site','Next').' >',
            'lastPageLabel'     => Yii::t('site','Last'),
            'pages'             => $pages,
            'maxButtonCount'    => 5,
        );
        return $defaults;
    } // }}}
    // {{{ getSupportedLocales
    public function getSupportedLocales()
    {
        return array(
            'en_gb' => Yii::t('site','English'),
            'de' => Yii::t('site','German')
        );        
    } // }}} 
    // {{{ getSupportedLocalesLinks
    public function getSupportedLocalesLinks()
    {
        return array(
            'en_gb' => CHtml::link(CHtml::image(Yii::app()->baseUrl.'/images/icons/flag_en_uk.png','UK Flag',array('style'=>'display:inline;vertical-align:middle;')),array('/site/selectLanguage','_lang'=>'en_gb'),array('title'=>Yii::t('site','Change language to English'))),
            'de' => CHtml::link(CHtml::image(Yii::app()->baseUrl.'/images/icons/flag_de.png','DE Flag',array('style'=>'display:inline;vertical-align:middle')),array('/site/selectLanguage','_lang'=>'de'),array('title'=>Yii::t('site','Change language to German'))),        
        );
    } // }}} 
    // {{{ newNote
    /**
     * Creates a new note.
     * This method attempts to create a new note based on the user input.
     * If the note is successfully created, the browser will be redirected
     * to show the created note.
     * @param MyModel Model the model that the new note belongs to
     * @return Note the note instance
     */
    protected function newNote($model)
    {
        $note=new Note;
        if(isset($_POST['ajax']))
        {
            echo CActiveForm::validate($note);
            Yii::app()->end();
        }
        if(isset($_POST['Note']))
        {
            $note->attributes=$_POST['Note'];
            if($model->addNote($note))
            {
                Yii::app()->user->setFlash('noteSubmitted',Yii::t('site','Your note has been added.'));
                $this->refresh();
            }
        }
        return $note;
    } // }}} 
    // {{{ actionDeleteAttachment
    public function actionDeleteAttachment()
    {
        if(!isset($_POST['file']))
            return;
        Yii::log("Delete Attachment: ".$_POST['file']); 
        if(is_file($_POST['file']))
            unlink($_POST['file']);
    } // }}} 
    // {{{ formatDateTime
    /**
     * Formats a Date/Time item
     *
     * Returns a blank string if date is '0000-00-00' or 0
     * 
     * @param mixed $attribute 
     * @param string $dateWidth 
     * @param string $timeWidth 
     * @access public
     * @return string
     */
    public function formatDateTime($attribute, $dateWidth='medium', $timeWidth='medium')
    {
        if($attribute=='0000-00-00' or $attribute==0)
            return '';
        return Yii::app()->dateFormatter->formatDateTime($attribute,$dateWidth,$timeWidth);
    } // }}} 
    // {{{ restoreSearchAdmin
    /**
     * Stores or restores attributes for $model->search in admin view
     * 
     * @param mixed $controller Instance of controller
     * @param mixed $model Instance of model
     * @access public
     * @return void
     */
    public function restoreSearchAdmin($controller,$model)
    {
        if(isset($_GET[get_class($model)])) {
            // DEBUG echo par($_GET[get_class($model)]);
            Yii::app()->user->setState(get_class($controller).'_admin',$_GET[get_class($model)]);
        } else {
            if(!is_null(Yii::app()->user->getState(get_class($controller).'_admin',null)))
                $_GET[get_class($model)] = Yii::app()->user->getState(get_class($controller).'_admin');
        }
    } // }}} 
    // {{{ actionSuggestItems
    public function actionSuggestItems()
    {
        if(!isset($_GET['model'])) return;
        if(!isset($_GET['modelAttribute'])) return;
        if(isset($_GET['q']) && ($keyword=trim($_GET['q']))!=='')
        {
            $modelOnject = new $_GET['model'];
            $items=$modelOnject->suggestItems($_GET['model'], $_GET['modelAttribute'], $keyword);
            if($items!==array())
                echo implode("\n",$items);
        }

    } // }}} 
}
